<?php

class Dapadarse extends Varien_Object {

    public $me;
    public $myId;
    public $facebook;
    private $session;
    private $db;
    
    const TOTAL_TARGETS_PER_USER = 5;
    
    public function __construct($facebookObj) 
    {
        $this->facebook = $facebookObj;
        $this->me = $this->facebook->api('me');
        $this->myId = $this->me['id'];
        $this->db = $this->_getDBSingleton();
        $this->session = new Data_session;
        $this->registerUser();
        $this->saveTargets();
    }
    
    private function _getDBSingleton()
    {
        return myDatabase::getInstance()
            ->setCredentials('root', 'root')->setHost('localhost')
            ->setDB('dapadarse')
            ->connect()
            ->recordQueries(true)
            ->setFetchMode('assoc');
    }
    
    public function registerUser()
    {
        if ($this->session->getRegisteredUser()) {
            return false;
        }
        $query = "INSERT IGNORE INTO `users` (`facebook_id`, `name`, `gender`, `locale`, `member_since`) 
            VALUES ('".$this->myId."', '".$this->me['name']."', '".$this->me['gender']."', '".$this->me['locale']."', now());";
        if ($this->db->execute($query)) {
            $this->session->setRegisteredUser(true);
        }
    }

    public function getFriends($userId) 
    {
        $getter = 'getFriendsOf_'.$userId;
        $setter = 'setFriendsOf_'.$userId;
        $friends = array();
        if ($this->session->$getter()) {
            $friends = $this->session->$getter();
        } else {
            $userFriends = $this->facebook->api($userId . '/friends');
            if (isset($userFriends['data'])) {
                $this->session->$setter($userFriends['data']);
                $friends = $userFriends['data'];
            }
        }
        return $friends;
    }
    
    public function getMyFriends() 
    {
        return $this->getFriends('me');
    }
    
    public function getName($userId) 
    {
        $user = $this->facebook->api($userId);
        if ($user && isset($user['name'])) {
            return $user['name'];
        }
    }
    
    public function isTarget($userId)
    {
        return in_array($userId, $this->getMyTargets());
    }
    
    public function getProfileImg($userId)
    {
        return 'https://graph.facebook.com/'.$userId.'/picture?width=148&height=148';
    }
        
    public function saveTargets() 
    {
        if ($this->_getSelectedTargets()) {
            $query = "REPLACE INTO  `targets` (`facebook_id` ,`targets`) VALUES ('".$this->myId."',  '".$this->_getSelectedTargets()."');";
            if ($this->db->execute($query)) {
                $this->session->unsMyTargets();
            }
        }
    }
    
    public function getMyTargets()
    {
        $targets = array();
        if ($this->session->getMyTargets()) {
            $targets = $this->session->getMyTargets();
        } else {
            $query = "SELECT `targets` FROM  `targets`  WHERE `facebook_id` = '".$this->myId."' LIMIT 1";
            $response = $this->db->execute($query)->getResults();
            if (isset($response[0]['targets']) && $targets = $response[0]['targets']) {
                $this->session->setMyTargets(json_decode($targets));
                $targets = json_decode($targets);
            }        
        }
        return $targets;
    }

    private function _getSelectedTargets() 
    {
        $friends = Helper::getPost('friend');
        if (is_array($friends)) {
            $friends = array_slice($friends, 0, self::TOTAL_TARGETS_PER_USER);
            return json_encode($friends);
        }
    }
    
    public function getMyFriendsIds()
    {
        $friends = array();
        foreach ($this->getMyFriends() as $friend) {
            $friends[] = $friend['id'];
        }
        return $friends;
    }
    
    public function getFansOfMine()
    {
        if ($this->session->getFansOfMine()) {
            $allFans = $this->session->getFansOfMine();
        } else {
            $myFriends = "'" . implode ("','", $this->getMyFriendsIds()) . "'";    
            $query = "SELECT `facebook_id` FROM `targets` WHERE `facebook_id` in (".$myFriends.") AND `targets` LIKE ('%".$this->myId."%');";
            $fans = $this->db->execute($query)->getResults();
            $allFans = array();
            foreach ($fans as $fan) {
                $allFans[] = $fan['facebook_id'];
            }
            $this->session->setFansOfMine($allFans);
        }        
        return $allFans;
    }
    
    public function getFansOfMinePreety()
    {
        $fansOfMine = $this->getFansOfMine();
        $allFans = array();
        foreach ($fansOfMine as $fan) {
            $allFans[] = array(
                'name' => $this->getName($fan),
                'id' => $fan,
            );
        }
        return $allFans;
    }
    
    public function getGoalsIds()
    {
        $fansOfMine = $this->getFansOfMine();
        $myTargets = $this->getMyTargets();
        return array_intersect($fansOfMine, $myTargets);
    }
    
    public function getGoals()
    {
        $goals = $this->getGoalsIds();
        $friends = array();
        foreach ($goals as $friend) {
            $friends[] = array(
                'name' => $this->getName($friend),
                'id' => $friend,
            );
        }
        return $friends;
    }
    
    public function __($string) 
    {
        $trans = $this->getLang() ? $this->getLang() : array();
        return isset($trans[$string]) ? $trans[$string] : $string;
    }
        
}
